<template>
  <div class="component-hot-search-add-or-update">
    <el-dialog
      v-model="visible"
      :title="
        !dataForm.hotSearchId
          ? $t('crud.addTitle')
          : $t('temp.modify')
      "
      :close-on-click-modal="false"
      :width="dialogWidth"
      @closed="dialogClosed"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="labelWidth"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-form-item
          :label="$t('shop.title')"
          prop="title"
        >
          <el-input
            v-model="dataForm.title"
            class="hot-search-input"
            controls-position="right"
            maxlength="50"

            show-word-limit
            :label="$t('shop.title')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('shop.content')"
          prop="content"
        >
          <el-input
            v-model="dataForm.content"
            class="hot-search-input"
            controls-position="right"
            maxlength="250"
            type="textarea"
            show-word-limit
            :label="$t('shop.content')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('hotSearch.seq')"
          prop="seq"
        >
          <el-input-number
            v-model="dataForm.seq"
            controls-position="right"
            :min="0"
            :max="999"
            :precision="0"
            :label="$t('hotSearch.seq')"
            @keydown="channelInputLimit"
            @blur="changeSeq"
          />
        </el-form-item>
        <el-form-item
          :label="$t('product.status')"
          prop="status"
        >
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">
              {{ $t("publics.normal") }}
            </el-radio>
            <el-radio :label="0">
              {{ $t("live.offline") }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >{{ $t("crud.filter.cancelBtn") }}</div>
          <div
            class="default-btn primary-btn"
            @click="onSubmit"
          >{{ $t("crud.filter.submitBtn") }}</div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const validateTitle = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shop.title') + $t('publics.noNull')))
  } else {
    callback()
  }
}
const validateContent = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('shop.content') + $t('publics.noNull')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  title: [
    { required: true, message: $t('shop.title') + $t('publics.noNull'), trigger: 'blur' },
    { validator: validateTitle, trigger: 'blur' }
  ],
  content: [
    { required: true, message: $t('shop.content') + $t('publics.noNull'), trigger: 'blur' },
    { validator: validateContent, trigger: 'blur' }
  ]
})

const dialogWidth = ref('')
const defWidth = 600
const labelWidth = localStorage.getItem('bbcLang') === 'en' ? '120px' : '80px'
onMounted(() => {
  dialogWidth.value = setDialogWidth(defWidth)
  window.onresize = () => {
    return (() => {
      dialogWidth.value = setDialogWidth(defWidth)
    })()
  }
})
const setDialogWidth = function (defWidthVal) {
  const val = document.body.clientWidth
  const def = defWidthVal || 850 // 默认宽度
  if (val < def) {
    return '97%'
  } else {
    return def + 'px'
  }
}

const dataFormRef = ref(null)
const dataForm = ref({
  hotSearchId: 0,
  title: '',
  content: '',
  recDate: '',
  seq: 0,
  status: 1
})
const visible = ref(false)
const init = (data) => {
  visible.value = true
  isSubmit.value = false
  if (data) {
    dataForm.value = Object.assign({}, data)
  } else {
    nextTick(() => {
      dataFormRef.value?.resetFields()
      dataForm.value = {
        hotSearchId: 0,
        title: '',
        content: '',
        recDate: '',
        seq: 0,
        status: 1
      }
    })
  }
}
// 表单提交
const page = {
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
}
const isSubmit = ref(false)
const onSubmit = () => {
  dataFormRef.value?.validate(valid => {
    if (valid) {
      const param = dataForm.value
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/admin/hotSearch'),
        method: param.hotSearchId ? 'put' : 'post',
        data: http.adornData(param)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList', page)
          }
        })
      }).catch((e) => {
        isSubmit.value = false
      })
    }
  })
}
// 清除表单验证
const dialogClosed = () => {
  dataFormRef.value?.clearValidate()
}

const channelInputLimit = (e) => {
  const key = e.key
  // 不允许输入'e'
  if (key === 'e' || key === '.' || key === '+' || key === '-') {
    e.returnValue = false
    return false
  }
  return true
}

const changeSeq = () => {
  if (!dataForm.value.seq) {
    dataForm.value.seq = 0
  }
}
defineExpose({ init })
</script>

<style lang="scss" scoped>
  div :deep(.el-textarea__inner) {
    padding-right: 56px;
  }
  .component-hot-search-add-or-update {
    .hot-search-input {
      :deep(.el-input__count) {
        right: 20px;
      }
      :deep(input){
        padding-right: 50px !important;
      }
    }
  }
</style>
